import { ref, computed, onMounted } from 'vue'
import { defineStore } from 'pinia'
import { login as apiLogin, getCurrentUser, getUserById } from '@/api/user'
import type { User, LoginParams } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(localStorage.getItem('token'))
  const currentUser = ref<User | null>(null)
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userInfo = computed(() => currentUser.value)

  // 方法
  // 登录
  const login = async (loginParams: LoginParams) => {
    loading.value = true
    try {
      const result = await apiLogin(loginParams)
      
      if (result.code === 200) {
        // 保存token
        token.value = result.data
        localStorage.setItem('token', result.data)
        
        // 获取用户信息
        await fetchCurrentUser()
        
        console.log('登录成功，token:', result.data)
        console.log('登录成功，用户信息:', currentUser.value)
        
        return { token: result.data, user: currentUser.value }
      } else {
        throw new Error(result.message || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    if (!token.value) return null
    
    loading.value = true
    try {
      const response = await getCurrentUser()
      
      if (response.code === 200) {
        currentUser.value = response.data
        console.log('获取用户信息成功:', response.data)
        
        // 将用户信息也保存到localStorage，以便在刷新页面时恢复
        localStorage.setItem('user_info', JSON.stringify(response.data))
        
        return response.data
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
      return null
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = () => {
    token.value = null
    currentUser.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user_info')
  }

  // 初始化 - 如果有token则获取用户信息
  const initialize = async () => {
    console.log('初始化用户状态, token:', token.value)
    
    // 尝试从localStorage恢复用户信息
    const savedUserInfo = localStorage.getItem('user_info')
    if (savedUserInfo) {
      try {
        currentUser.value = JSON.parse(savedUserInfo)
        console.log('从本地存储恢复用户信息:', currentUser.value)
      } catch (e) {
        console.error('解析本地用户信息失败:', e)
      }
    }
    
    // 如果有token，尝试重新获取最新的用户信息
    if (token.value) {
      try {
        await fetchCurrentUser()
      } catch (e) {
        console.error('初始化时获取用户信息失败:', e)
      }
    }
  }

  return { 
    token, 
    currentUser, 
    loading, 
    isLoggedIn, 
    userInfo, 
    login, 
    logout, 
    fetchCurrentUser, 
    initialize 
  }
}) 